const { reject } = require("lodash");

const PENDING = 'pending'; // 等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'rejected'; // 失败

class Mypromise {
  constructor(executor) {
    try {
      executor(this.resolve, this.reject)
    } catch (error) {
      this.reject(error)
    }
  }
  // promise状态
  status = PENDING
  // 成功值
  value = undefined
  // 失败报错
  error = undefined
  // 成功回调
  successCallback = [];
  // 失败回调
  failCallback = [];
  resolve = value => {
    // 如果不是等待状态直接返回
    if (this.status !== PENDING) {
      return
    }
    // 状态更改为成功
    this.status = FULFILLED
    // 保存成功的值
    this.value = value
    // 循环判断回调是否存在，存在就执行
    while (this.successCallback.length) this.successCallback.shift()()
  }
  reject = error => {
    // 如果不是等待状态直接返回
    if (this.status !== PENDING) {
      return
    }
    // 状态更改为失败
    this.status = REJECTED
    // 保存失败原因
    this.error = error
    // 循环判断回调是否存在，存在就执行
    while (this.failCallback.length) this.failCallback.shift()()
  }
  then(successCallback, failCallback) {
    successCallback = successCallback ? successCallback : value => value
    failCallback = failCallback ? failCallback : error => { throw error }
    // 返回promise对象
    let promise = new Mypromise((resolve, reject) => {
      // 判断状态
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try {
            let x = successCallback(this.value)
            // 实现链式调用
            resolvePromise(promise, x, resolve, reject)
          } catch (error) {
            reject(error)
          }
        }, 0)
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let x = failCallback(this.error)
            resolvePromise(promise, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        }, 0)
      } else {// 等待
        // 将成功回调暂存
        this.successCallback.push(() => {
          setTimeout(() => {
            try {
              let x = successCallback(this.value)
              // 实现链式调用
              resolvePromise(promise, x, resolve, reject)
            } catch (error) {
              reject(error)
            }
          }, 0)
        })
        // 将失败回调暂存
        this.failCallback.push(() => {
          setTimeout(() => {
            try {
              let x = failCallback(this.error)
              resolvePromise(promise, x, resolve, reject)
            } catch (e) {
              reject(e)
            }
          }, 0)
        })
      }
    })
    return promise
  }
  finally(callback) {
    return this.then(value => {
      return Mypromise.resolve(callback()).then(() => value)
    }, error => {
      return Mypromise.reject(callback()).then(() => { throw error })
    })
  }
  catch(failCallback) {
    return this.then(undefined, failCallback)
  }
  static resolve(value) {
    // 如果是Mypromise实例 直接返回
    if (value instanceof Mypromise) {
      return value
    }
    // 不是的话就生成一个Mypromise对象返回
    return new Mypromise(resolve => resolve(value))
  }
  static all(array) {
    // 储存结果
    let result = []
    let index = 0
    return new Mypromise((resolve, reject) => {
      function addData(index, value) {
        result[index] = value
        index++
        if (index === array.length) {
          resolve(result)
        }
      }
      // 轮训执行每一个item，直到全部保存后执行resolve，返回一个Mypromise对象
      for (let i = 0; i < array.length; i++) {
        let temp = array[i]
        if (temp instanceof Mypromise) {
          temp.then(value => { addData(i, value) }, error => reject(error))
        } else {
          addData(i, temp)
        }
      }
    })
  }
}

function resolvePromise(promise, x, resolve, reject) {
  if (promise === x) {
    return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
  }
  // x是promise对象 继续调用then方法
  if (x instanceof Mypromise) {
    x.then(resolve, reject)
  } else {
    // x是普通值 直接返回值
    resolve(x)
  }
}

module.exports = Mypromise